<?php

namespace App\Helpers;

use App\Exceptions\BusinessException;
use Illuminate\Http\JsonResponse;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;

trait ApiResponse
{
    /**
     * 成功
     * @param null $data
     * @param array $codeResponse
     * @param string $customInfo
     * @return JsonResponse
     */
    public function success($data = null, array $codeResponse = ResponseEnum::HTTP_SUCCESS, string $customInfo = ''): JsonResponse
    {
        return $this->jsonResponse('success', $codeResponse, $data, $customInfo);
    }

    /**
     * 失败
     * @param array $codeResponse
     * @param string $customInfo
     * @param null $data
     * @return JsonResponse
     */
    public function fail(array $codeResponse = ResponseEnum::HTTP_ERROR, string $customInfo = '', $data = null): JsonResponse
    {
        return $this->jsonResponse('fail', $codeResponse, $data, $customInfo);
    }

    /**
     * json响应
     * @param $status string 状态
     * @param $codeResponse array 状态码
     * @param $data mixed 数据
     * @param $customInfo string 自定义信息
     * @return JsonResponse
     */
    private function jsonResponse(string $status, array $codeResponse, mixed $data, string $customInfo): JsonResponse
    {
        [$code, $message] = $codeResponse;
        return response()->json([
            'status' => $status,
            'error' => $code,
            'html' => $customInfo ?: $message,
            'data' => $data ?: null,
        ]);
    }

    /**
     * 成功分页返回
     * @param $result
     * @return mixed
     */
    protected function successPage($result): mixed
    {
        if ($result instanceof LengthAwarePaginator) {
            return [
                'total' => $result->total(), // 数据总量
                'pages' => ceil($result->total() / $result->perPage()), // 总页数
                'currentPage' => $result->currentPage(), // 当前页数
                'psize' => $result->perPage(), // 当前条数
                'list' => $result->items(), // 数据列表
            ];
        }
        if ($result instanceof Collection) {
            $result = $result->toArray();
        }
        if (!is_array($result)) {
            return $result;
        }
        $total = count($result);
        return [
            'total' => $total,
            'pages' => 1,
            'currentPage' => 1,
            'psize' => $total,
            'list' => $result
        ];
    }

    /**
     * 业务异常返回
     * @param array $codeResponse
     * @param string $customInfo
     * @throws BusinessException
     */
    public function throwBusinessException(array $codeResponse = ResponseEnum::HTTP_ERROR, string $customInfo = ''): void
    {
        throw new BusinessException($codeResponse, $customInfo);
    }
}
